package de.stefanocke.roo.wicket.base

import org.springframework.roo.metadata.MetadataItem

import static de.stefanocke.roo.wicket.MidUtils.*
import static de.stefanocke.roo.wicket.base.MetadataFilter.*

import static extension de.stefanocke.roo.xtend.Counter.*
import static extension de.stefanocke.roo.xtend.RooExtensions.*
import static extension java.util.Collections.*

class MetadataFilter {
	
	def static <M extends MetadataItem> filterClosest(Iterable<M> iterable, String mid){
		filterClosest(mid).apply(iterable)
	}
	def static <M extends MetadataItem> (Iterable<M>)=>Iterable<M> filterClosest(String mid){
		//closure that filters the metadata that is in the package hierarchy closest to the requesting one
		[Iterable<M> iterable | {
			if(iterable.empty) iterable else {					
				val max = iterable.map[commonPackagePrefixLength(mid, it.id)].toSet.max	
				iterable.filter[commonPackagePrefixLength(mid, it.id) == max]
			}
		}]
	}
	
	def static commonPackagePrefixLength(String mid, String candidateId) {
		val requestingType = getJavaTypeForMid(mid).fqn.split("[\\.]")
		val candidateType = getJavaTypeForMid(candidateId).fqn.split("[\\.]")

		Math::min(requestingType.size, candidateType.size).counter.findFirst[
			!requestingType.get(it).equals(candidateType.get(it))
		]
	
	}
	
}